package jdk.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;


/**
 * 实现一个简单的可重入锁(基于Object的wait(),notifyAll())
 */
public class MyReentrantLock implements Lock {

    private boolean hasLocked = false;
    private Thread nowLockThread = null;
    private int entrantCount = 0;

    @Override
    public synchronized void lock() {
        while (hasLocked && !Thread.currentThread().equals(nowLockThread)){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if(Thread.currentThread().equals(nowLockThread)){
            System.out.println("线程"+nowLockThread.getName()+"重入锁");
            entrantCount++;
        }

        if(!hasLocked){
            hasLocked = true;
            nowLockThread = Thread.currentThread();
            entrantCount++;
            System.out.println("线程"+nowLockThread.getName()+"获取锁");
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public synchronized void unlock() {
        if(Thread.currentThread().equals(nowLockThread)){
            if(hasLocked){
                entrantCount--;
                if(entrantCount==0){
                    System.out.println("线程"+nowLockThread.getName()+"释放锁");
                    hasLocked = false;
                    nowLockThread = null;
                    notifyAll();
                }else{
                    System.out.println("线程"+nowLockThread.getName()+"重出锁");
                }
            }
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
